﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Graphics.Display;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.ApplicationSettings;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel;
using Windows.UI.Popups;



// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace StudyTime_1
{
    
        
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class Page1 : StudyTime_1.Common.LayoutAwarePage
    {
            //List<IStorageFile> ItemsList;
           
            //StorageFile storage;
            //private string fileName;
            private string filePath;

            bool dtmSet = false;

            DataTransferManager dataTransferManager;
            private FileActivatedEventArgs fileTransport = null;

            

           

        public Page1()
        {
            this.InitializeComponent();

           
                RegisterForShare();



                checkForFile();
                setDefaults();
                
           
        }

       
        private static void setDefaults()
        {
            App.delFile = null;
            App.quizFile = null;
            App.storage = null;
            App.stFile = null;
        }

        public void setInArgs(FileActivatedEventArgs a)
        {
            fileTransport = a;
            checkForFile();
        }

        private void checkForFile()
        {
           
            
            if (fileTransport != null)
            {
                IStorageItem n = fileTransport.Files[0];
                string s = fileTransport.Files[0].Name;



                if (s.Contains(".studycardxml"))
                {
                    Frame.Navigate(typeof(studyCards1));
                }
                if (s.Contains(".quizxml"))
                {
                    Frame.Navigate(typeof(quizMe));
                }
            }
        }


        private void RegisterForShare()
        {
            try
            {
               dataTransferManager = DataTransferManager.GetForCurrentView();

                dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager,
                    DataRequestedEventArgs>(this.ShareStorageItemsHandler);
                App.shareSet = true;
            }
            catch (Exception e)
            {
                string s = e.ToString();

            }
        }

        //private void registerSettings()
        //{
        //    SettingsPane.GetForCurrentView().CommandsRequested += Page1_CommandsRequested;
        //}

        //void Page1_CommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        //{
        //    args.Request.ApplicationCommands.Add(new SettingsCommand("s", "Study Time Settings", (p) => { cfoSettings.IsOpen = true; }));
        //}



        



        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

       
        private void quizMe_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(quizMe));

        }

        private void quizBuilder_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(quizBuilder1));
        }

        private void studyCards_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(studyCards1));
        }

        private void cardBuilder_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(cardBuilder));

        }

       async private void pageRoot_Loaded(object sender, RoutedEventArgs e)
        {
            Storyboard sb = this.FindName("page1Story") as Storyboard;
            if (sb != null)
            {
                sb.Begin();
            }

            if (App.scoreSet == false)
            {

                await classes.serializer.readScoreXML();
                App.scoreSet = true;
            }


         
        }

        private void getResolution()
        {

            double height = buttonGrid.ActualHeight;
            double width = buttonGrid.ActualWidth;
            ResolutionScale rScale = DisplayProperties.ResolutionScale;

          

           // pageTitle.Text = rScale.ToString();
        }


      



        private void ShareStorageItemsHandler(DataTransferManager sender, DataRequestedEventArgs e)
        {


            if (App.fileName != null)
            {
                try
                {
                    DataRequest request = e.Request;
                    request.Data.Properties.Title = "Study Time";
                    request.Data.Properties.Description = "Shared from Study Time Windows 8 App.";

                    request.Data.SetStorageItems(App.ItemsList);
                }
                finally
                {
                    App.ItemsList.Clear();
                }
            }

           
        }




        async private void selection()
        {
            {
                {

                    FileOpenPicker openPicker = new FileOpenPicker();
                    openPicker.ViewMode = PickerViewMode.List;
                    openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
                    openPicker.FileTypeFilter.Add(".studycardxml");
                    openPicker.FileTypeFilter.Add(".quizxml");

                    App.storage1 = await openPicker.PickSingleFileAsync();

                    if (null != App.storage1)
                    {
                        // Application now has read/write access to the picked file
                        App.fileName = App.storage1.Name;
                        filePath = App.storage1.Path;

                        App.ItemsList.Add(App.storage1);
                        
                        
                        //loadData(cardList);
                        ////questions.Text = fileName + " Click Load if this is the correct File";
                        //errorBox.Text = "";
                        

                        DataTransferManager.ShowShareUI();

                    }
                    else
                    {
                        // errorBox.Text = "File was not returned";
                    }
                }


            }
        }

        private  void Share_Click(object sender, RoutedEventArgs e)
        {
            selection();
        }

        private void HELP_Click(object sender, RoutedEventArgs e)
        {
            if (imgScroll.Visibility == Visibility.Collapsed)
            {
                imgScroll.Visibility = Visibility.Visible;
                HELP.Visibility = Visibility.Visible;
                HELP.Content = "Back";
            }
            else
            {
                imgScroll.Visibility = Visibility.Collapsed;
                HELP.Visibility = Visibility.Collapsed;
                //HELP.Content = "HELP!";
            }

        }

         private void rmvAd_Click(object sender, RoutedEventArgs e)
        {

            removeAds.setNofication();

            //MessageDialog startDialog = new MessageDialog("If you do not want to see ads again please select Go To Store, otherwise press cancel", "Remove Ads?");
            //UICommand store = new UICommand("Go To Store", onStore);
            //UICommand cancel = new UICommand("Cancel");

            //startDialog.Commands.Add(store);
            //startDialog.Commands.Add(cancel);

            //await startDialog.ShowAsync();
        }

         private void manageDeck_Click(object sender, RoutedEventArgs e)
         {
             this.Frame.Navigate(typeof(deckManage));
         }

         private void Scores_Click(object sender, RoutedEventArgs e)
         {
             this.Frame.Navigate(typeof(myScores));
         }

        //async public void onStore(object command)
        //{
        //    Uri pageUri = new Uri("http://apps.microsoft.com/webpdp/app/study-time/ee4a5766-52ff-471d-b743-3ecd3157eee7");
        //    await Windows.System.Launcher.LaunchUriAsync(pageUri); 

        //}



    }
}
